<?php
namespace Home\Controller;
use Common\Model\ActivityModel;
use Common\Model\QgsSpecialAdvertstatusModel;
use Common\Model\SpecialStoreModel;
use Common\Model\StorePageModel;
use Common\Model\StoreShortcutMenuModel;
use Home\Model\GoodsModel;
use Think\Controller;
use Home\Event\WeixinEvent;
use Home\Event\JssdkEvent;
use Home\Controller\BaseController;

//set_time_limit(100);
class StoreController extends BaseController {
    //static $error = 0;
    public $app_id;
    public $secret;
    public function __construct(){
        parent::__construct();
        $this->app_id = C('APPID');
        $this->secret = C('SECRET');
    }

    use ActivityModel;
    /**
     * @param $source 入口.1-微信 0-其他
     * stortSelect : 1-已经选择过店铺不在切换店铺 ，0或者null -- 没定位没选择切换店铺。
     */
    public function index(){

        $local_id = '';
        if ($_REQUEST['local_id']) {
            $local_id = intval($_REQUEST['local_id']);
        }

        $top_local_id = 11; // 如果是其他店铺，切换全国送的时候需要传一个其他门店的local_id方便切换
        if ($_REQUEST['top_local_id']) {
            $top_local_id = intval($_REQUEST['top_local_id']);
        }

        if($local_id != session('home_local_id')){
            session('home_local_id',null);
            session('home_local_id',$local_id);
        }

        // 判断是游客没有默认门店就跳转
        if (empty($local_id)) {
            $local_id = session('t_userInfo')['default_local_id'];
            if(!$local_id){
                redirect(U('/First/stortSelect/'));
            }
        }


        if($top_local_id != session('top_home_local_id')){
            session('top_home_local_id',null);
            session('top_home_local_id',$top_local_id);
        }

        //查询店铺信息
        $storeData = M('webpos_local_store')->cache(true,86400, 'redis')->where(['local_id'=>$local_id])->find();

        if (empty($storeData)) {
            redirect(U('/First/stortSelect/'));
        }

        if($storeData['is_self'] == 1){
            $this->assign('is_self',1);
        }else{
            $this->assign('is_self',0);
        }

        // 查询全国送店铺
        $self_store = M('webpos_local_store')->cache(true,86400, 'redis')->where(['is_self' => 1])->find();

        // 查询除开全国送的其他店铺
        $top_self_store = M('webpos_local_store')->cache(true,86400, 'redis')->where(['local_id' => $top_local_id])->find();

        //dump($storeData);
        $source = session('source');
        $stortSelect = session('stortSelect');
        //dump($stortSelect);
        $ak = C('BAIDU_AK');
        //$jssdk = A('Jssdk','Event');
        //$signPackage = $jssdk->GetSignPackage();

        // 轮播
        $carousel = $this->carousel($local_id);
        $this->assign(['carousel' => $carousel]);

        // 快捷菜单
        $shortcut = new StoreShortcutMenuModel();
        $shortcutMsg = $shortcut->getMsgFromLocalId($local_id);
        $this->assign(['shortcutMsg' => $shortcutMsg]);

        // 店铺自定义分享的logo
        $sharewhere=['local_id'=>$local_id,'type'=>0];
        $sharelog = M('weixin_share_logo')->where($sharewhere)->find();
        $this->assign('share_log',$sharelog['image']);

        // 广告模块
        $specialadvert =new QgsSpecialAdvertstatusModel();
        $advertData = $specialadvert->advert($local_id);
        $this->assign($advertData);

        // 专题
        $special =new SpecialStoreModel();
        $specialMsg = $special->getMsgFromLocalId($local_id);
        $this->assign(['specialMsg' => $specialMsg]);

        // 马上买
        $maShangMai = new StorePageModel();
        $maShangMaiMsg = $maShangMai->maShangMai($local_id);
        $this->assign(['maShangMaiMsg' => $maShangMaiMsg]);

        // 推荐
        $tuiJianMsg = $maShangMai->tuiJian($local_id);
        $this->assign(['tuiJianMsg' => $tuiJianMsg]);

        // 店铺关注
        $member_like_store = M('b2c_member_like_store')->where(['local_id' => $local_id,'status'=>1])->count();
        $member_id = session('userInfo')['member_id'];
        if($member_id){
            $member_store_data = M('b2c_member_like_store')->where(['local_id' => $local_id,'member_id'=>$member_id,'status'=>1])->find();
        }else{
            $member_store_data = false;
        }

        //查询店铺所属区域传到页面上
        //$this->assign(['signPackage' => $signPackage]);
        $this->assign(['ak' => $ak]);
        $this->assign('source',$source);
        $this->assign('storeData',$storeData);
        $this->assign('stortSelect',$stortSelect);
        $this->assign('self_store',$self_store);
        $this->assign('member_store_data',$member_store_data);
        $this->assign('member_like_store',$member_like_store);
//        $this->assign('top_local_id',$top_local_id);
        $this->assign('top_self_store',$top_self_store);
        $this->display();
//        $this->buildHtml("index22.html",'',"Store:index");
    }

    /**
     * 轮播
     */
    public function carousel($local_id){
        $store_carousel = M('store_carousel');
        return $store_carousel->cache(true, 86400, 'redis')->where(['local_id' => $local_id, 'status' => '1'])->order(['order' => 'asc'])->select();
    }

    /**
     * 专题模板
     */
    public function viewTemplate() {
        $id = I('param.id');
        if (!$id) {
            $this->error('缺少参数');
        }
        $local_id = I('local_id');
        //$jssdk = A('Jssdk','Event');
        //$signPackage = $jssdk->GetSignPackage();
        //$this->assign('signPackage', $signPackage);
        //$url = C('HTTP_HOST').'/index.php/home/First/index?url='.urlencode(C('HTTP_HOST').U('Store/viewTemplate',array('id'=>$id), '')).'#wechat_redirect';
        $url = 'http://'.C('HTTP_HOST').U('Store/viewTemplate',array('id'=>$id,'local_id'=>$local_id), '').'#wechat_redirect';
        $this->assign('link', $url);
        /** 2.0 版本的分享链接 todo
         * https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx538369e3fac7783f&redirect_uri=http://m.yichen666.com//weixin/authorize&response_type=code&scope=snsapi_userinfo&state=/special/72#wechat_redirect
         */
        $list = array();

        $info = M('b2c_special_store')
            ->alias('a')
            ->join(C('DB_PREFIX').'b2c_special_template b on a.tid=b.id', 'LEFT')
            ->field('a.*, b.title b_title, b.title2 b_title2, b.title3 b_title3, b.title4 b_title4, b.title5 b_title5,b.img_url b_img_url')
            ->where(array('a.id'=>$id))
            ->find();
        if ($info) {

            $info['title'] = $info['b_title'] ? $info['b_title']: $info['title'];
            $info['title2'] = $info['b_title2'] ? $info['b_title2']: $info['title2'];
            $info['title3'] = $info['b_title3'] ? $info['b_title3']: $info['title3'];
            $info['title4'] = $info['b_title4'] ? $info['b_title4']: $info['title4'];
            $info['title5'] = $info['b_title5'] ? $info['b_title5']: $info['title5'];
            $info['img_url'] = $info['b_img_url'] ? $info['b_img_url']: $info['img_url'];
        }

        if ($info['typeids']) {
            $cart_ids = unserialize($info['typeids']);
            if (is_array($cart_ids) && !empty($cart_ids)) {
                foreach ($cart_ids as $key => $item) {
                    $pids_un = M('b2c_special_type_store')->where(array('type_id'=>$item))->find();
                    if (!empty($pids_un['goodids'])) {
                        $pids = unserialize($pids_un['goodids']);
                        $list[$key]['type_id'] = $pids_un['type_id'];
                        $list[$key]['type_name'] = $pids_un['type_name'];
                        $items = M('b2c_store_product a')
                            ->join(C('DB_PREFIX').'b2c_products b on a.product_id=b.product_id')
                            ->field('a.store_pid,b.spec_info,a.goods_id, a.store, a.price,a.marketprice, b.name')
                            ->where(array('store_pid'=>array('in',$pids), 'b.disabled' => 'false'))
                            ->order("FIELD (`store_pid`, ".implode(',', $pids).")")
                            ->select();

                        //商品促销价格
                        $this->GoodsPromotion($items, $local_id);
                        $list[$key]['data'] = $items;
                    }
                }
            }

        }

        $this->assign('info', $info);
        $this->assign('list', $list);
        //dump(I('local_id'));
        $this->assign('local_id', $local_id);
        $this->display(T('Admin@Special:viewTemplate'));
    }

    /**
     * 快捷菜单产品列表
     */
    public function goods_list(){
        $id = I('id', '', intval());  // 栏目id
        $type = I('type', '', htmlspecialchars()); // carousel为轮播类型

        $local_id = I('local_id', '1'); // 店铺id
        //查询店铺信息
//        $storeData = M('webpos_local_store')->where(['local_id'=>$local_id])->find();

//        if (!empty($type) && $type == 'carousel') {
//            $m = M('store_carousel');
//        } else {
//            $m = M('store_shortcut_menu');
//        }
//
//        $where = [
//            'id' => $id,
//            'local_id' => $local_id
//        ];
//        $shortcut = $m->where($where)->find();
//
//
//
//        $value = unserialize($shortcut['value']);
//        $value = implode(',', $value);
//
//        $page = max(I('get.p'), 1);
//        $num = max(I('get.num'), 10);
//
//        $b2c_store_product = M('b2c_store_product a');
//
//        $count = $b2c_store_product->join(C('DB_PREFIX').'b2c_products b on a.product_id = b.product_id', 'left')
//            ->where(['a.store_pid' => ['in', $value], 'a.store_status' => 'true'])
//            ->count();

//        $Page = new \Think\Page($count, $num);
//
//        $Page->setConfig('next','加载更多>>>');
//        $Page->setConfig('theme','%DOWN_PAGE%');
//
//        $show = $Page->show();

//        $totalPage = ceil($count/$num); // 总页面数
//
//
//        $productMsg = $b2c_store_product->join(C('DB_PREFIX').'b2c_products b on a.product_id = b.product_id', 'left')
//        ->where(['a.store_pid' => ['in', $value], 'a.store_status' => 'true'])
//        ->page($page, $num)
//        ->select();
//
//        foreach ($productMsg as &$v) {
//            $v['image'] = getThumb($v['goods_id']);
//        }
//
//        echo json_encode([
//            'data' => $productMsg,
//            'totalPage' => $totalPage, // 总页数
//            'count' => $count, // 总个数
//            'page' => $page, // 第几页
//        ]);

//        $this->assign([
//           'productMsg' => $productMsg,
//            'storeData' => $storeData
//        ]);

        $this->assign([
           'id' => $id,
            'local_id' => $local_id,
            'type' => $type
        ]);
        $this->display();
    }

    /**
     * ajax
     */
    public function ajax_goods_list(){
        $id = I('id', '', intval());
        $type = I('type', '', htmlspecialchars()); // carousel为轮播类型

        $local_id = I('local_id');

        if (!empty($type) && $type == 'carousel') {
            $m = M('store_carousel');
        } else {
            $m = M('store_shortcut_menu');
        }

        $where = [
            'id' => $id,
            'local_id' => $local_id
        ];
        $shortcut = $m->where($where)->find();

        $value = unserialize($shortcut['value']);
        $value = implode(',', $value);

        $page = max(I('get.p'), 1);
        $num = max(I('get.num'), 10);

        $where_store_product['a.store_pid'] = ['in', $value];
        $where_store_product['a.local_id'] = $local_id;
        $where_store_product['a.store_status'] = 'true'; // 店铺上架的商品
        $b2c_store_product = M('b2c_store_product a');

        $count = $b2c_store_product->join(C('DB_PREFIX').'b2c_products b on a.product_id = b.product_id AND b.disabled = "false"', 'left')
            ->where($where_store_product)
            ->count();

        $totalPage = ceil($count/$num); // 总页面数


        $productMsg = $b2c_store_product->join(C('DB_PREFIX').'b2c_products b on a.product_id = b.product_id AND b.disabled = "false"', 'left')
            ->where($where_store_product)
            ->field('a.*,b.name,b.spec_info')
            ->page($page, $num)
            ->select();

        $GoodsModel = new GoodsModel();
        foreach ($productMsg as $k=>&$v) {
            //商品促销
            $info = $this->checkGoodsIsPromotion($local_id, $v['store_pid']);
            if (!empty($info)){
                $v['proPrice'] = number_format($info['price'], 2, '.', '');
            }else{
                $v['proPrice'] = '';
            }
            $v['image'] = getThumb($v['goods_id']);
            $v['label_info'] = getProductLabel($v['local_id'], $v['product_id']);

            // 判断闪购
            $flashGoods = $GoodsModel->checkGoodsIsStarBuy($v['store_pid']);
            if (!empty($flashGoods)) {
                $productMsg[$k]['flashPrice'] = $flashGoods['promotion_price'];
                $productMsg[$k]['store'] = $flashGoods['initnum'];
                $productMsg[$k]['freez'] = 0;
            }else{
                $productMsg[$k]['flashPrice'] = '';
            }
            // 判断组合促销
            $checkProductIsGroupPromotion = checkProductIsGroupPromotion($v['store_pid'], $v['local_id']);
            $productMsg[$k]['groupPromotion'] = $checkProductIsGroupPromotion;
        }

        echo json_encode([
            'data' => $productMsg,
            'totalPage' => $totalPage, // 总页数
            'count' => $count, // 总个数
            'page' => $page, // 第几页
        ]);
    }


    public function test() {
        $local_id = I('local_id', '1');
        if (empty($local_id) || $local_id == '' || $local_id == null) {
            $local_id = 1;
        }
        $special =new SpecialStoreModel();
        $specialMsg = $special->getMsgFromLocalId($local_id);
        dump($specialMsg);
    }

}